package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.UserDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.service.UserDishService;
import com.sky.service.UserService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDishServiceImpl implements UserDishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private FlavorMapper flavorMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<DishVO> findDishByCategoryId(Long categoryId) {

        //使用redis进行缓存，来解决高并发问题
        //这里的逻辑是:先去redis中去查找看有没有，有直接返回，
        // 没有则去数据库中请求，请求的数据再保存在redis中
        //这里需要注意，在每次变更信息时，需要清除redis中的缓存。
        String key="dish_"+categoryId;
        List<DishVO> redisDish = (List<DishVO>)redisTemplate.opsForValue().get(key);
        if (redisDish!=null&&redisDish.size()>0){

            return redisDish;
        }


        List<Dish> dishList = dishMapper.userselectByCategoryId(categoryId);
        List<DishVO>dishVOS=new ArrayList<>();
        for (Dish dish : dishList) {
            DishVO dishVO=new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            List<DishFlavor> byDishId = flavorMapper.findByDishId(dish.getId());
            dishVO.setFlavors(byDishId);
            dishVOS.add(dishVO);
        }
        redisTemplate.opsForValue().set(key,dishVOS);
        return dishVOS;
    }
}
